package values.level
{
import flash.errors.IllegalOperationError;
import flash.events.EventDispatcher;

import values.events.ItemValueEvent;
import values.events.LevelEvent;
import values.item.ResourceItemValue;

[Event(name="levelChanged", type="values.events.LevelEvent")]

public class DynamicLevelValue extends EventDispatcher
{	
	/**
	 * Level 
	 */	
	protected var _level:int = 0;
	
	public function get level():int
	{
		return _level;
	}
	
	public function get isMaxLevel():Boolean
	{
		return level == maxLevel;
	}
	
	public function get maxLevel():int
	{
		throw new IllegalOperationError("maxLevel getter should be overrided.");
	}
	
	public function getLevelValue(lv:int):LevelValue
	{
		throw new IllegalOperationError("getLevelValue method should be overrided.");
	}
	
	protected var _resourceVO:ResourceItemValue;
	
	public function get resourceVO():ResourceItemValue
	{
		return _resourceVO;
	}
	
	public function get resource():Number
	{
		return resourceVO.num;
	}
	
	public function set resource(value:Number):void
	{
		resourceVO.num = value;
		resourceVO.forceUpdate();
	}
	
	/**
	 * Prev level required exp 
	 */	
	protected var _prevResource:Number = 0;
	
	public function get prevResource():Number
	{
		return _prevResource;
	}
	
	/**
	 * Next level required exp 
	 */	
	protected var _nextResource:Number = 0;
	
	public function get nextResource():Number
	{
		return _nextResource;
	}
	
	public function init(lv:int, resVO:ResourceItemValue):void
	{
		_level = lv;
		
		_resourceVO = resVO;
		resourceVO.addEventListener(ItemValueEvent.NUM_CHANGED, resourceChangedHandler);
		
		updateNextResource();
	}
	
	public function dispose():void
	{
		if (resourceVO)
		{
			resourceVO.removeEventListener(ItemValueEvent.NUM_CHANGED, resourceChangedHandler);
			_resourceVO = null;
		}
	}
	
	protected function updateNextResource():void
	{
		if (_level < maxLevel)
		{
			_prevResource = getLevelValue(_level).requiredResource;
			_nextResource = getLevelValue(_level + 1).requiredResource;
		}
		else
		{
			_nextResource = getLevelValue(maxLevel).requiredResource;
		}
	}
	
	protected function checkLevelWithResource():void
	{
		if (resource >= _nextResource)
		{
			_level ++;
			if (_level >= maxLevel)
			{
				_level = maxLevel;
				return;
			}
			updateNextResource();
			checkLevelWithResource();
		}
		else
		{
			return;
		}
	}
	
	protected function resourceChangedHandler(event:ItemValueEvent):void
	{
		if (resource >= nextResource && !isMaxLevel)
		{			
			_level ++;
			updateNextResource();
			checkLevelWithResource();
						
			this.dispatchEvent(new LevelEvent(LevelEvent.LEVEL_CHANGED, this));
		}
	}
	
}
}





